package hu.gar.core.service.impl;

import hu.gar.common.service.UserService;
import hu.gar.core.dao.RoleDao;
import hu.gar.core.dao.UserDao;
import hu.gar.core.dao.UserToRoleDao;
import hu.gar.core.entity.User;
import hu.gar.vo.RoleVO;
import hu.gar.vo.UserVO;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service("userService")
@Transactional(propagation = Propagation.REQUIRED)
public class UserServiceImpl implements UserService {

	private static final long serialVersionUID = -5959005433558687290L;

	@Autowired
	UserDao userDao;

	@Autowired
	UserToRoleDao userToRoleDao;

	@Autowired
	RoleDao roleDao;

	@Override
	public List<UserVO> getAllUser() {
		return userDao.toVO(userDao.findAll());

	}

	@Override
	public void removeUser(Long id) {
		userDao.delete(id);

	}

	@Override
	public void updateUser(UserVO userVO) {
		userDao.update(userDao.toEntity(userVO));

	}

	@Override
	public UserVO addUser(UserVO userVO) {
		return userDao.toVO(userDao.create(userDao.toEntity(userVO)));
	}

	@Override
	public List<RoleVO> getRolesByUserId(Long id) {
		return roleDao.toVO(userToRoleDao.findByUserId(id));
	}

	@Override
	public void addRoleToUser(Long userId, Long roleId) {
		userToRoleDao.addRoleToUser(userId, roleId);

	}

	@Override
	public void removeRoleFromUser(Long userId, Long roleId) {
		userToRoleDao.removeRoleFromUser(userId, roleId);

	}

	@Override
	public UserVO findByName(String name) {
		User findByName = userDao.findByName(name);
		return userDao.toVO(findByName);
	}

	@Override
	public void authenticate(String username, String password) {
		User user = userDao.findByName(username);
		if (user == null) {
			throw new BadCredentialsException(username);
		}
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		if (!encoder.matches(password, user.getPassword())) {
			throw new BadCredentialsException(username);
		}
	}

}
